package net.esj.basic.view;

import java.util.Collections;
import java.util.Map;

import net.esj.basic.core.view.RequestUtils;
import net.esj.basic.plugins.view.FacadeAware;
import net.esj.basic.pojo.op.Administrator;
import net.esj.basic.pojo.op.Operator;
import net.esj.basic.pojo.system.ApplicationClass;
import net.esj.basic.pojo.system.ApplicationClass.APPLICATION_CAN;
import net.esj.basic.pojo.system.ApplicationClass.FieldAttribute;
import net.esj.basic.service.provider.ApplicationProvider;
import net.esj.basic.core.business.aware.op.OperatorAuthAware;

public abstract class AbstractPluginPageAction<P,V> extends PageAction<P, V> implements FacadeAware,OperatorAuthAware{

	private String template;
	private String theme;
	private String namespace;
	
	private Operator operator;
	
	private boolean cb = false;
	
	public String searchbar(){
		return SUCCESS;
	}
	
	public String getTemplate() {
		return template;
	}
	public void setTemplate(String template) {
		this.template = template;
	}
	public String getTheme() {
		return theme;
	}
	public void setTheme(String theme) {
		this.theme = theme;
	}
	public String getNamespace() {
		return namespace;
	}
	public void setNamespace(String namespace) {
		this.namespace = namespace;
	}
	
	@Override
	public Operator getOperator() {
		Operator op = operator;
		if(op!=null){
			return op;
		}else{
			try {
				Administrator admin = (Administrator) getSessionUser(Class.forName("cn.ausong.atmat.pojo.AgencyUser"));
				return admin;
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			return null;
		}
	}
	@Override
	public void setOperator(Operator operator) {
		this.operator = operator;
	}
	
	@Override
	public boolean isAllowed(String uri) {
		if(getOperator() instanceof Administrator){
			if(uri.indexOf("?")>0){
				String url = uri.substring(0, uri.indexOf("?"));
				String params = uri.substring(uri.indexOf("?")+1);
				Map map = RequestUtils.parseQueryString(params);
				return ((Administrator)getOperator()).isAllowed(url, map);
			}else{
				return ((Administrator)getOperator()).isAllowed(uri, Collections.EMPTY_MAP);
			}
		}
		return false;
	}
	public boolean isCb() {
		return cb;
	}
	public void setCb(boolean cb) {
		this.cb = cb;
	}
	
	public boolean canApp(String field,String key){
		ApplicationClass clazz = ApplicationProvider.getClass(entityClass);
		if(clazz==null){
			return true;//默认都可以
		}
		FieldAttribute attribute = clazz.getAttribute(field,getRequest().getRequestURL().toString(),getRequest().getParameterMap());
		if(attribute==null){
			return true;
		}
		switch(APPLICATION_CAN.valueOf(key.toUpperCase())){
		case ADD:
			return attribute.isAdd();
		case EDIT:
			return attribute.isEdit();
		case LIST:
			return attribute.isList();
		case SORT:
			return attribute.isSort();
		case VIEW:
			return attribute.isView();
		}
		return true;
	}
}
